package net.xju3_4.dao;

import com.alibaba.fastjson2.util.DateUtils;
import net.xju3_4.common.utils.JdbcUtilsV1;
import net.xju3_4.common.utils.PageInfo;
import net.xju3_4.entity.OrderDTOEntity;
import net.xju3_4.entity.OrderEntity;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderDao {


    //    订单分页查找
    public PageInfo<OrderEntity> orderPageList(String carId, String userId, String status, String merchantId, int pageNum, int pageSize) {
        Connection conn = JdbcUtilsV1.getConnection();
        String sql = "select id,user_id userId,car_id carId,merchant_id merchantId,start_time startTime,end_time endTime," +
                "actual_start_time actualStartTime,actual_end_time actualEndTime,rent_days rentDays,daily_rent dailyRent," +
                "estimated_total_amount estimatedTotalAmount,overtime_fee overtimeFee,damage_fee damageFee," +
                "final_amount finalAmount,`status` from rental_order where 1=1  ";
        if (carId != null && !carId.isEmpty()) {
            sql += (" AND car_id =") + (carId) ;
        }

        if (userId != null && !userId.isEmpty()) {
            sql += (" AND user_id= ") + (userId);
        }

        if (status != null && !status.isEmpty()) {
            sql += (" AND status = '") + (status) + ("'");
        }
        sql += " and merchant_id="+merchantId+" order by id desc";
//        sql += " and merchant_id=1 order by id desc";
        sql += " limit " + (pageNum - 1) * pageSize + "," + pageSize;
        List<OrderEntity> users = JdbcUtilsV1.executeQuery(conn, OrderEntity.class, sql);
        String countSql = "select count(*) from rental_order where merchant_id="+merchantId;
        long count = JdbcUtilsV1.executeQueryOneValue(countSql);
        PageInfo<OrderEntity> pageInfo = new PageInfo<>(pageNum, pageSize, (int) count, users);
        return pageInfo;
    }


//    订单新增
    public boolean insert(OrderEntity order) {
        Connection conn = JdbcUtilsV1.getConnection();
        String sql = "INSERT INTO rental_order(user_id ,car_id ,merchant_id ,start_time ,end_time ,actual_start_time " +
                ",actual_end_time ,rent_days ,daily_rent ,estimated_total_amount ,overtime_fee ,damage_fee ,final_amount " +
                ",`status`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        int i = JdbcUtilsV1.executeUpdate(conn, sql, order.getUserId(),order.getCarId(),order.getMerchantId(),
                order.getStartTime(),
                order.getEndTime(),
                order.getActualStartTime(),
                order.getActualEndTime(),
                order.getRentDays(),order.getDailyRent(), order.getEstimatedTotalAmount(),order.getOvertimeFee(),order.getDamageFee(),order.getFinalAmount(),order.getStatus());
        JdbcUtilsV1.close();
        return i>0;
    }
//  订单删除
    public boolean orderDelete(int id) {
        Connection conn = JdbcUtilsV1.getConnection();
        String sql = "delete from rental_order where id = ? ";
        int i = JdbcUtilsV1.executeUpdate(conn, sql, id);
        return i>0;
    }

//  订单修改
    public boolean orderUpdate(OrderEntity order) {
        Connection conn = JdbcUtilsV1.getConnection();
        String sql = "update rental_order set";
        boolean ifFist = true;
        if (order.getCarId() != null && !order.getCarId().isEmpty()){
            sql += " car_id = '" + order.getCarId() + "'";
            ifFist = false;
        }
//        if (order.getUserId() != null && !order.getUserId().isEmpty()){
          if (order.getUserId() != null){
            if (!ifFist){
                sql += ",";
            }
            sql += " user_id = '" + order.getUserId() + "'";
            ifFist = false;
        }
        if (order.getMerchantId() != null && !order.getMerchantId().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " merchant_id = '" + order.getMerchantId() + "'";
            ifFist = false;
        }
        if (order.getStartTime() != null){
            if (!ifFist){
                sql += ",";
            }
            sql += " start_time = '" + DateUtils.format(order.getStartTime()) + "'";
            ifFist = false;
        }
        if (order.getEndTime() != null){
            if (!ifFist){
                sql += ",";
            }
            sql += " end_time = '" + DateUtils.format(order.getEndTime()) + "'";
            ifFist = false;
        }
        if (order.getActualStartTime() != null ){
            if (!ifFist){
                sql += ",";
            }
            sql += " actual_start_time = '" + DateUtils.format(order.getActualStartTime()) + "'";
            ifFist = false;
        }
        if (order.getActualEndTime() != null){
            if (!ifFist){
                sql += ",";
            }
            sql += " actual_end_time = '" + DateUtils.format(order.getActualEndTime()) + "'";
            ifFist = false;
        }
        if (order.getRentDays() != null && !order.getRentDays().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " rent_days = '" + order.getRentDays() + "'";
            ifFist = false;
        }
        if (order.getDailyRent() != null && !order.getDailyRent().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " daily_rent = '" + order.getDailyRent() + "'";
            ifFist = false;
        }
        if (order.getEstimatedTotalAmount() != null && !order.getEstimatedTotalAmount().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " estimated_total_amount = '" + order.getEstimatedTotalAmount() + "'";
            ifFist = false;
        }
        if (order.getOvertimeFee() != null && !order.getOvertimeFee().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " overtime_fee = '" + order.getOvertimeFee() + "'";
            ifFist = false;
        }
        if (order.getDamageFee() != null && !order.getDamageFee().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " damage_fee = '" + order.getDamageFee() + "'";
            ifFist = false;
        }
        if (order.getFinalAmount() != null && !order.getFinalAmount().isEmpty()){
            if (!ifFist){
                sql += ",";
            }
            sql += " final_amount = '" + order.getFinalAmount() + "'";
        }
//        if (order.getStatus() != null && !order.getStatus().isEmpty()){
          if (order.getStatus() != null){
            if (!ifFist){
                sql += ",";
            }
            sql += " status = '" + order.getStatus() + "'";
        }
        sql += " where id = " + order.getId();
        int i = JdbcUtilsV1.executeUpdate(conn, sql);
        return i>0;
    }

    public Map<String, Integer> count() {
        String sql = "select count(*) as totalOrder from rental_order";
        Long totalOrderCount = JdbcUtilsV1.executeQueryOneValue( JdbcUtilsV1.getConnection(), sql);
        sql = "select count(*) as activeOrder from rental_order where status = 5";
        Long activeOrderCount = JdbcUtilsV1.executeQueryOneValue(JdbcUtilsV1.getConnection(), sql);
        Long forbidOrderCount = totalOrderCount-activeOrderCount;
        if(totalOrderCount == null) totalOrderCount = 0L;
        if(activeOrderCount == null) activeOrderCount = 0L;
        if(forbidOrderCount == null) forbidOrderCount = 0L;
        Map<String, Integer> map = new HashMap<>();
        map.put("totalOrder", Math.toIntExact(totalOrderCount));
        map.put("activeOrder", Math.toIntExact(activeOrderCount));
        map.put("forbidOrder", Math.toIntExact(forbidOrderCount));
        return map;


    }


//    依照条件分页查询订单
public PageInfo<OrderDTOEntity> PageList(String realname, String merchantName, String orderId, Integer pageNo, Integer pageSize) {
    // 使用StringBuilder优化SQL拼接
    StringBuilder sqlBuilder = new StringBuilder("SELECT " +
            "    rental_order.id, " +
            "    rental_order.user_id AS userId, " +
            "    rental_order.car_id AS carId, " +
            "    rental_order.merchant_id AS merchantId, " +
            "    rental_order.start_time AS startTime, " +
            "    rental_order.end_time AS endTime, " +
            "    rental_order.actual_start_time AS actualStartTime, " +
            "    rental_order.actual_end_time AS actualEndTime, " +
            "    rental_order.rent_days AS rentDays, " +
            "    rental_order.daily_rent AS dailyRent, " +
            "    rental_order.estimated_total_amount AS estimatedTotalAmount, " +
            "    rental_order.overtime_fee AS overtimeFee, " +
            "    rental_order.damage_fee AS damageFee, " +
            "    rental_order.final_amount AS finalAmount, " +
            "    user.real_name AS realName, " +
            "    merchant.merchant_name AS merchantName, " +
            "    user.username AS userUsername, " +
            "    merchant.username AS merchantUsername, " +
            "    rental_order.status " +
            "FROM rental_order " +
            "INNER JOIN user ON rental_order.user_id = user.id " +
            "INNER JOIN merchant ON rental_order.merchant_id = merchant.id ");

    List<Object> params = new ArrayList<>();
    List<String> conditions = new ArrayList<>();

    // 构建查询条件（避免多余的AND和WHERE）
    if (realname != null && !realname.trim().isEmpty()) {
        conditions.add("user.real_name LIKE ?");
        params.add("%" + realname.trim() + "%");
    }

    if (merchantName != null && !merchantName.trim().isEmpty()) {
        conditions.add("merchant.merchant_name LIKE ?");
        params.add("%" + merchantName.trim() + "%");
    }

    // 处理订单ID（数字校验+去空格）
    if (orderId != null && !orderId.trim().isEmpty() && orderId.trim().matches("\\d+")) {
        conditions.add("rental_order.id = ?");
        params.add(Integer.parseInt(orderId.trim()));
    }

    // 动态添加WHERE条件（只有存在条件时才添加）
    if (!conditions.isEmpty()) {
        sqlBuilder.append("WHERE ").append(String.join(" AND ", conditions));
    }

    // 添加分页（确保LIMIT前有空格）
    sqlBuilder.append(" LIMIT ?, ?");
    params.add((pageNo - 1) * pageSize);
    params.add(pageSize);

    // 执行主查询
    List<OrderDTOEntity> orders = JdbcUtilsV1.executeQuery(OrderDTOEntity.class, sqlBuilder.toString(), params.toArray());
    String sqlcount = "SELECT COUNT(*) " +
            "FROM rental_order " +
            "INNER JOIN user ON rental_order.user_id = user.id " +
            "INNER JOIN merchant ON rental_order.merchant_id = merchant.id ";
    Long count = JdbcUtilsV1.executeQueryOneValue(sqlcount);
    return new PageInfo<>(pageNo, pageSize,Math.toIntExact(count),orders);




}
}


